package com.hang.gymmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hang.gymmanager.entity.SeatEntity;
import com.hang.gymmanager.exception.BusinessException;
import com.hang.gymmanager.mapper.SeatMapper;
import com.hang.gymmanager.service.SeatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class SeatServiceImpl extends ServiceImpl<SeatMapper, SeatEntity> implements SeatService {


    /**
     * 锁座方法
     * @param activityId
     * @param orderId
     * @param type
     * @param count
     * @return
     */
    @Override
    public List<Map<String , Integer>> lockSeat(Integer activityId,
                                                Long orderId,
                                                Integer userId,
                                                Integer type,
                                                Integer count) {
        List<Map<String , Integer>> result = new ArrayList<>();
        QueryWrapper<SeatEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SeatEntity::getActivityId,activityId)
                .eq(SeatEntity::getType,type)
                .isNull(SeatEntity::getUserId)
                .orderByAsc(SeatEntity::getId)
                .last("limit "+count);
        List<SeatEntity> seatEntities = this.getBaseMapper().selectList(wrapper);
        if(seatEntities.size()<count){
            throw new BusinessException("座位余票不足，请重试");
        }
        //把座位变成已预定的
        seatEntities.stream().forEach(e->{
            e.setUserId(userId);
            e.setOrderId(orderId);

            Map<String,Integer> temp = new HashMap<>();
            temp.put("area",e.getAreaId());
            temp.put("row",e.getSeatRow());
            temp.put("column",e.getSeatColumn());
            result.add(temp);
        });
        this.saveOrUpdateBatch(seatEntities);
        return result;
    }
}
